<?php

/*
 *
 * config:
 * doc-id: Document ID des zu rendernden Dokuments
 * lang-id: Sprachen ID, nur beachtet, wenn session variable s_currentLang nicht gesetzt ist
 *
 *
 *
 */

m2import('base/ApplicationContext.php');
m2import('phpinchains/Filter.php');
m2import('phpinchains/psp/ViewDispatcher.php');
m2import('base/templateEngine/CMSDocument.php');
m2import('base/templateEngine/DocumentContext.php');
m2import('base/templateEngine/TemplateEngine.php');
m2import('base/templateEngine/CacheKeyBuilder.php');

/**
 * Filter mit XICS template engine
 */
/* Configuration:
  <conf:filterParam name="buildMode" value="cache|export|print|preview|editor"/>
  <conf:filterParam name="doc-id" value="\d+"/>
  <conf:filterParam name="medium" value="|.xml|.pdf|..."/>
  <conf:filterParam name="doc-path" value="path/to/doc/without/leading_slash"/>
  <conf:filterParam name="lang-name" value="de|en|..."/>
  <conf:filterParam name="default-lang" value="de|en|..."/>
  <conf:filterParam name="do-process" value="true|false"/> default: false (for setting up environment for editor actions: editor actions redirect to the editor)
  <conf:filterParam name="site-id" value="\d+"/>
  <conf:filterParam name="404-page" value="404"/>
  <conf:filterParam name="default-page" value="index"/>
 */
class ResizeImageFilter extends phpinchains_Filter {


    function send404 () {
        header("HTTP/1.0 404 Not Found");
        print "<html><title>Image not found</title></head><body><h1>Oooops! - Image not found!</h1></body></html>";
    }

    function sendHeader() {
        if (isset($this->config['cache-headers']) && $this->config['cache-headers']=='true') {
            header("Cache-Control: max-age=3600, must-revalidate");
            header("Expires: " . gmdate("D, d M Y H:i:s", time()+86400) . " GMT");
            header("Pragma: cache");
        }
        switch (strtolower($this->config['file-extension'])) {
            case 'gif':
                header("Content-Type: image/gif");
                break;
            case 'jpeg':
            case 'jpg':
                header("Content-Type: image/jpeg");
                break;
            case 'png':
                header("Content-Type: image/png");
                break;
            case 'swf':
                header('Content-Type: application/x-shockwave-flash');
                print file_get_contents($filename);
                return true;
            case 'mp4':
                header('Content-Type: video/mp4');
                print file_get_contents($filename);
                return true;
        }
    }

    /**
     * @var array
     */
    function doFilter(env $env, phpinchains_FilterChain $chain) {
        $resizeW = $this->config['width']  == 0 ? 1000000 : $this->config['width'];
        $resizeH = $this->config['height'] == 0 ? 1000000 : $this->config['height'];
        if (strlen($resizeW) && strlen($resizeH)) {
            $cache = new base_templateEngine_Cache(base_templateEngine_Cache::$IMAGE_DIR, true);
            $mcache = new base_templateEngine_Cache(base_templateEngine_Cache::$IMAGEMETA_DIR, false);
            $imagekey = base_templateEngine_CacheKeyBuilder::buildImageKey($this->config['file'], $this->config['width'], $this->config['height']);
            $metakey = base_templateEngine_CacheKeyBuilder::buildImageMetaKey($this->config['file']);
            if (!$this->config['width'] && !$this->config['height'] && $this->sendHeader()) return;
            if (!$cache->test($imagekey)) {
                $filename = $this->config['file-path'].$this->config['file'].'.'.$this->config['file-extension'];
                // send type header
                // file requested in original size
                if (file_exists($filename) && !$this->config['width'] && !$this->config['height']) {
                    $this->sendHeader();
                    print file_get_contents($filename);
                    return;
                }
                if (!$mcache->test($metakey)) {
                    $this->send404();
                    return;
                }
                $metadata = $mcache->load($metakey);
                // Width 200 is used for xics internal
                if ($this->config['width'] != 200 && !in_array($this->config['width'].'_'.$this->config['height'], $metadata)) {
                    $this->send404();
                    return;
                }
                try {
                    switch (strtolower($this->config['file-extension'])) {
                        case 'gif':
                            $source = @imagecreatefromgif($filename);
                            break;
                        case 'jpeg':
                        case 'jpg':
                            $source = @imagecreatefromjpeg($filename);
                            break;
                        case 'png':
                            $source = @imagecreatefrompng($filename);
                            break;
                        default:
                            return;
                    }
                    $width  = @imagesx($source);
                    $height = @imagesy($source);
                    if ($width > $resizeW && $height > $resizeH) {
                        $newwidth  = $resizeW;
                        $newheight = round($height * ($resizeW / $width));
                        if ($newheight > $resizeH) {
                            $newheight = $resizeH;
                            $newwidth  = round($width * ($resizeH / $height));
                        }
                    } elseif ($width > $resizeW) {
                        $newwidth  = $resizeW;
                        $newheight = round($height * ($resizeW / $width));
                    } elseif ($height > $resizeH) {
                        $newheight = $resizeH;
                        $newwidth  = round($width * ($resizeH / $height));
                    } else {
                        $newheight = $height;
                        $newwidth  = $width;
                    }
                    $thumb = imagecreatetruecolor($newwidth, $newheight);
                    $color = imagecolorallocate($thumb, 255, 255, 255);
                    imagefill($thumb, 0, 0, $color);
                    imagecolortransparent($thumb, $color);
                    imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
                    ob_start();
                    switch (strtolower($this->config['file-extension'])) {
                        case 'gif':
                            imagegif($thumb);
                            break;
                        case 'jpeg':
                        case 'jpg':
                            imagejpeg($thumb, null, 100);
                            break;
                        case 'png':
                            imagepng($thumb);
                            break;
                        default:
                            return;
                    }
                    $this->sendHeader();
                    $img = ob_get_flush();
                    $cache->save($imagekey, $img);
                } catch (Exception $e) {print $e->getMessage();}
            } else {
                $this->sendHeader();
                print $cache->load($imagekey);
            }
        }
    }

    function init(& $config) {
        $fields = array('file-extension', 'file', 'file-path', 'width', 'height', 'cache-headers');
        foreach ($fields as $field)
            $this->config[$field] = isset($config[$field]) ? $config[$field] : '';
    }

}
